package com.conversationboard.controller.subscriptions;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.SecurityChecks;
import com.conversationboard.model.User;

@WebServlet(name = "SubscribeToBoardControllerServlet", urlPatterns = "/SubscribeToBoardControllerServlet")
public class SubscribeToBoardControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -5958945511800802858L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			User user = User.get(request.getUserPrincipal().getName());
			int subscribeToBoardId = Integer.parseInt(request.getParameter("boardid"));

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			user.subscribe(subscribeToBoardId);

			request.setAttribute("message", "You have successfully subscribed to this board.");

			RequestDispatcher dispatcher = request.getRequestDispatcher("Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
